package vetxsoft.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import vetxsoft.bean.ClienteBean;
import vetxsoft.entity.Mascota;
import vetxsoft.system.IVetexsoftSystem;

/**
 * @author user
 */
@FacesConverter(forClass = Mascota.class, value = "MascotaConvertor")
public class MascotaConvertor implements Converter {

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
        if (value == null || value.trim().equalsIgnoreCase("Seleccione...") || value.trim().length() == 0) {
            return null;
        }
        try {
            IVetexsoftSystem vetexsoftSystem = ((ClienteBean) fc.getApplication().getELResolver().getValue(fc.getELContext(), null, "clienteBean")).getVetexsoftSystem();
            Mascota mascota = vetexsoftSystem.buscarMascota(value);
            return mascota;
        } catch (Exception _exc) {
            return null;
        }
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Mascota) {
            Mascota mascota = (Mascota) value;
            return mascota.getCodigo() + "";
        } else {
            throw new IllegalArgumentException("object " + value + " is of type " + value.getClass().getName() + "; expected type: " + Mascota.class.getName());
        }
    }
}